/*

Summary:
A reader priority lock for sharing resource between threads.

Remark:
WARNING, this class isn't been tested well. It may has some 
potential problems.

The algorithm is listed below.

Writer:
P(Wmutex)
	Do something for write...
V(Wmutex)

Reader:
P(Rmutex)
	if (readCount == 0) P(Wmutex)
	++readCount
V(Rmutex)
	Do something for read...
P(Rmutex)
	--readCount
	if (readCount == 0) V(Wmutex)
V(Rmutex)

Version:
0.0.2

LastUpdatedDate:
2012-09-06

CreatedDate:
2012-09-04

*/

#pragma once

#include <Windows.h>


namespace Zaf {
namespace Sync {



class ReaderPriorityLock {

public:
	ReaderPriorityLock();
	~ReaderPriorityLock();

	void ReaderEnter();
	void ReaderLeave();

	void WriterEnter();
	void WriterLeave();

private:
	ReaderPriorityLock(const ReaderPriorityLock&);
	const ReaderPriorityLock& operator=(const ReaderPriorityLock&);

	void P(HANDLE mutex) {
		WaitForSingleObject(mutex, INFINITE);
	}

	void V(HANDLE mutex) {
		ReleaseSemaphore(mutex, 1, nullptr);
	}

	DWORD m_readerCount;

	HANDLE m_readerCountLock;
	HANDLE m_writerLock;
};



}
}